/**
 * @file mqtt_config_loader.c
 * @brief MQTT配置加载器实现
 * @details 从配置文件加载MQTT连接和主题配置
 * 
 * @author zyb
 * @date 2025-10-30
 * @version 1.0
 */

#include "../include/mqtt_config_loader.h"
#include "../../../common/logs/include/logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LOG_MODULE_NAME "MQTT_CONFIG"

/* ==================== 辅助函数 ==================== */

/**
 * @brief 安全的字符串复制函数
 */
static inline void safe_strncpy(char *dest, const char *src, size_t dest_size) {
    if (dest == NULL || src == NULL || dest_size == 0) {
        return;
    }
    size_t src_len = strlen(src);
    size_t copy_len = (src_len < dest_size - 1) ? src_len : (dest_size - 1);
    memcpy(dest, src, copy_len);
    dest[copy_len] = '\0';
}

/* ==================== 默认配置值 ==================== */

#define DEFAULT_MQTT_PORT 1883
#define DEFAULT_MQTT_KEEPALIVE 60
#define DEFAULT_MQTT_QOS MQTT_QOS_1
#define DEFAULT_MQTT_CLEAN_SESSION true
#define DEFAULT_MQTT_USE_TLS false
#define DEFAULT_DATA_REPORT_INTERVAL 5
#define DEFAULT_STATUS_REPORT_INTERVAL 30
#define DEFAULT_MESSAGE_BUFFER_SIZE 1024
#define DEFAULT_MESSAGE_QUEUE_SIZE 100

/**
 * @brief 加载MQTT配置
 */
int mqtt_config_load(mqtt_full_config_t* config, const char* config_file) {
    if (config == NULL || config_file == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "配置参数为空");
        return -1;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "加载MQTT配置文件: %s", config_file);
    
    // 初始化配置结构
    memset(config, 0, sizeof(mqtt_full_config_t));
    LOG_DEBUG(LOG_MODULE_NAME, "配置结构初始化完成，大小: %zu 字节", sizeof(mqtt_full_config_t));
    
    // 设置默认值
    config->connection.port = DEFAULT_MQTT_PORT;
    config->connection.keepalive = DEFAULT_MQTT_KEEPALIVE;
    config->connection.qos = DEFAULT_MQTT_QOS;
    config->connection.clean_session = DEFAULT_MQTT_CLEAN_SESSION;
    config->connection.use_tls = DEFAULT_MQTT_USE_TLS;
    config->data_report_interval = DEFAULT_DATA_REPORT_INTERVAL;
    config->status_report_interval = DEFAULT_STATUS_REPORT_INTERVAL;
    config->message_buffer_size = DEFAULT_MESSAGE_BUFFER_SIZE;
    config->message_queue_size = DEFAULT_MESSAGE_QUEUE_SIZE;
    
    // 打开配置文件
    FILE* fp = fopen(config_file, "r");
    if (fp == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "无法打开配置文件: %s", config_file);
        return -1;
    }
    
    char line[1024];
    int line_num = 0;
    
    while (fgets(line, sizeof(line), fp)) {
        line_num++;
        
        // 去除首尾空白字符
        char* p = line;
        while (*p == ' ' || *p == '\t') p++;
        if (*p == '\0' || *p == '\n' || *p == '#') {
            continue; // 空行或注释行
        }
        
        // 解析键值对
        char key[128], value[512];
        if (sscanf(p, "%127[^=]=%511[^\n]", key, value) != 2) {
            continue; // 跳过无效行
        }
        
        // 去除键和值的首尾空白
        char* key_end = key + strlen(key) - 1;
        while (key_end > key && (*key_end == ' ' || *key_end == '\t')) {
            *key_end = '\0';
            key_end--;
        }
        
        char* value_start = value;
        while (*value_start == ' ' || *value_start == '\t') value_start++;
        char* value_end = value_start + strlen(value_start) - 1;
        while (value_end > value_start && (*value_end == ' ' || *value_end == '\t' || *value_end == '\n')) {
            *value_end = '\0';
            value_end--;
        }
        
        // 解析MQTT配置项
        if (strcmp(key, "mqtt_broker") == 0 || strcmp(key, "server") == 0) {
            safe_strncpy(config->connection.broker, value_start, sizeof(config->connection.broker));
            LOG_DEBUG(LOG_MODULE_NAME, "解析配置 - Broker: %s", config->connection.broker);
        } else if (strcmp(key, "mqtt_port") == 0 || strcmp(key, "port") == 0) {
            config->connection.port = (uint16_t)atoi(value_start);
            LOG_DEBUG(LOG_MODULE_NAME, "解析配置 - Port: %u", config->connection.port);
        } else if (strcmp(key, "mqtt_client_id") == 0 || strcmp(key, "client_id") == 0) {
            safe_strncpy(config->connection.client_id, value_start, sizeof(config->connection.client_id));
            LOG_DEBUG(LOG_MODULE_NAME, "解析配置 - ClientID: %s", config->connection.client_id);
        } else if (strcmp(key, "mqtt_username") == 0 || strcmp(key, "user") == 0 || strcmp(key, "username") == 0) {
            safe_strncpy(config->connection.username, value_start, sizeof(config->connection.username));
            LOG_DEBUG(LOG_MODULE_NAME, "解析配置 - Username: %s", config->connection.username);
        } else if (strcmp(key, "mqtt_password") == 0 || strcmp(key, "password") == 0) {
            safe_strncpy(config->connection.password, value_start, sizeof(config->connection.password));
            LOG_DEBUG(LOG_MODULE_NAME, "解析配置 - Password: %s", "******");
        } else if (strcmp(key, "mqtt_keepalive") == 0) {
            config->connection.keepalive = (uint16_t)atoi(value_start);
            LOG_DEBUG(LOG_MODULE_NAME, "解析配置 - KeepAlive: %u", config->connection.keepalive);
        } else if (strcmp(key, "mqtt_qos") == 0) {
            config->connection.qos = (mqtt_qos_t)atoi(value_start);
            LOG_DEBUG(LOG_MODULE_NAME, "解析配置 - QoS: %d", config->connection.qos);
        } else if (strcmp(key, "mqtt_clean_session") == 0) {
            config->connection.clean_session = (strcmp(value_start, "y") == 0 || strcmp(value_start, "true") == 0);
            LOG_DEBUG(LOG_MODULE_NAME, "解析配置 - CleanSession: %s", config->connection.clean_session ? "是" : "否");
        } else if (strcmp(key, "mqtt_use_tls") == 0) {
            config->connection.use_tls = (strcmp(value_start, "y") == 0 || strcmp(value_start, "true") == 0);
        } else if (strcmp(key, "mqtt_topic_control") == 0) {
            safe_strncpy(config->topic_control, value_start, sizeof(config->topic_control));
        } else if (strcmp(key, "mqtt_topic_data") == 0) {
            safe_strncpy(config->topic_data, value_start, sizeof(config->topic_data));
        } else if (strcmp(key, "mqtt_topic_status") == 0) {
            safe_strncpy(config->topic_status, value_start, sizeof(config->topic_status));
        } else if (strcmp(key, "mqtt_topic_alarm") == 0) {
            safe_strncpy(config->topic_alarm, value_start, sizeof(config->topic_alarm));
        } else if (strcmp(key, "device_id") == 0) {
            safe_strncpy(config->device_id, value_start, sizeof(config->device_id));
        } else if (strcmp(key, "station_id") == 0) {
            safe_strncpy(config->station_id, value_start, sizeof(config->station_id));
        } else if (strcmp(key, "device_type") == 0) {
            safe_strncpy(config->device_type, value_start, sizeof(config->device_type));
        } else if (strcmp(key, "data_report_interval") == 0) {
            config->data_report_interval = (uint32_t)atoi(value_start);
        } else if (strcmp(key, "status_report_interval") == 0) {
            config->status_report_interval = (uint32_t)atoi(value_start);
        } else if (strcmp(key, "message_buffer_size") == 0) {
            config->message_buffer_size = (uint32_t)atoi(value_start);
        } else if (strcmp(key, "message_queue_size") == 0) {
            config->message_queue_size = (uint32_t)atoi(value_start);
        }
    }
    
    fclose(fp);
    
    LOG_DEBUG(LOG_MODULE_NAME, "MQTT配置加载完成");
    return 0;
}

/**
 * @brief 打印MQTT配置
 */
void mqtt_config_print(const mqtt_full_config_t* config) {
    if (config == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "配置为空");
        return;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "==================== MQTT配置 ====================");
    LOG_DEBUG(LOG_MODULE_NAME, "MQTT Broker配置:");
    LOG_DEBUG(LOG_MODULE_NAME, "  Broker地址: %s", config->connection.broker);
    LOG_DEBUG(LOG_MODULE_NAME, "  端口: %u", config->connection.port);
    if (strlen(config->connection.client_id) > 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "  客户端ID: %s", config->connection.client_id);
    }
    if (strlen(config->connection.username) > 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "  用户名: %s", config->connection.username);
    }
    LOG_DEBUG(LOG_MODULE_NAME, "  保持连接: %u秒", config->connection.keepalive);
    LOG_DEBUG(LOG_MODULE_NAME, "  QoS级别: %d", config->connection.qos);
    LOG_DEBUG(LOG_MODULE_NAME, "  清除会话: %s", config->connection.clean_session ? "是" : "否");
    LOG_DEBUG(LOG_MODULE_NAME, "  使用TLS: %s", config->connection.use_tls ? "是" : "否");
    
    // 只打印有值的主题配置
    if (strlen(config->topic_control) > 0 || 
        strlen(config->topic_data) > 0 || 
        strlen(config->topic_status) > 0 || 
        strlen(config->topic_alarm) > 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "MQTT主题配置:");
        if (strlen(config->topic_control) > 0) {
            LOG_DEBUG(LOG_MODULE_NAME, "  控制指令主题: %s", config->topic_control);
        }
        if (strlen(config->topic_data) > 0) {
            LOG_DEBUG(LOG_MODULE_NAME, "  数据上报主题: %s", config->topic_data);
        }
        if (strlen(config->topic_status) > 0) {
            LOG_DEBUG(LOG_MODULE_NAME, "  状态上报主题: %s", config->topic_status);
        }
        if (strlen(config->topic_alarm) > 0) {
            LOG_DEBUG(LOG_MODULE_NAME, "  告警上报主题: %s", config->topic_alarm);
        }
    }
    
    // 只打印有值的设备信息
    if (strlen(config->device_id) > 0 || 
        strlen(config->station_id) > 0 || 
        strlen(config->device_type) > 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "设备信息:");
        if (strlen(config->device_id) > 0) {
            LOG_DEBUG(LOG_MODULE_NAME, "  设备ID: %s", config->device_id);
        }
        if (strlen(config->station_id) > 0) {
            LOG_DEBUG(LOG_MODULE_NAME, "  站点ID: %s", config->station_id);
        }
        if (strlen(config->device_type) > 0) {
            LOG_DEBUG(LOG_MODULE_NAME, "  设备类型: %s", config->device_type);
        }
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "数据上报配置:");
    LOG_DEBUG(LOG_MODULE_NAME, "  数据上报周期: %u秒", config->data_report_interval);
    LOG_DEBUG(LOG_MODULE_NAME, "  状态上报周期: %u秒", config->status_report_interval);
    LOG_DEBUG(LOG_MODULE_NAME, "================================================");
}

/**
 * @brief 验证MQTT配置
 */
int mqtt_config_validate(const mqtt_full_config_t* config) {
    if (config == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "配置为空");
        return -1;
    }
    
    // 验证MQTT broker地址
    if (strlen(config->connection.broker) == 0) {
        LOG_ERROR(LOG_MODULE_NAME, "MQTT Broker地址为空");
        return -1;
    }
    
    // 验证端口
    if (config->connection.port == 0) {
        LOG_ERROR(LOG_MODULE_NAME, "MQTT端口无效");
        return -1;
    }
    
    // 验证客户端ID
    if (strlen(config->connection.client_id) == 0) {
        LOG_ERROR(LOG_MODULE_NAME, "MQTT客户端ID为空");
        return -1;
    }
    
    // 验证主题配置
    if (strlen(config->topic_control) == 0) {
        LOG_ERROR(LOG_MODULE_NAME, "控制指令主题为空");
        return -1;
    }
    
    if (strlen(config->topic_data) == 0) {
        LOG_ERROR(LOG_MODULE_NAME, "数据上报主题为空");
        return -1;
    }
    
    // 验证设备ID
    if (strlen(config->device_id) == 0) {
        LOG_ERROR(LOG_MODULE_NAME, "设备ID为空");
        return -1;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "配置验证通过");
    return 0;
}

